package com.chen.yygh.user.api;

import com.alibaba.fastjson.JSONObject;
import com.chen.yygh.common.exception.YyghException;
import com.chen.yygh.common.helper.JwtHelper;
import com.chen.yygh.common.result.Result;
import com.chen.yygh.common.result.ResultCodeEnum;
import com.chen.yygh.model.user.UserInfo;
import com.chen.yygh.user.service.UserInfoService;
import com.chen.yygh.user.utils.ConstantWxPropertiesUtil;
import com.chen.yygh.user.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {

    @Autowired
    private UserInfoService userInfoService;


    //微信扫码后需要回调的方法
    @GetMapping("callback")
    public String callback(String code,String state) throws UnsupportedEncodingException {
        //第一步 获取临时票据 code
        System.out.println("微信授权服务器回调。。。。。。");
        System.out.println("state = " + state);
        System.out.println("code = " + code);
        //第二步 使用code 和 微信 id 和秘钥，请求微信的固定地址，得到两个值
        //使用code 和 appid 以及 appscrect 换取 access_token 以及 openid

        //使用code和appid以及appscrect换取access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");

        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantWxPropertiesUtil.WX_OPEN_APP_ID,
                ConstantWxPropertiesUtil.WX_OPEN_APP_SECRET,
                code);

        String result = null;
        try {
            result = HttpClientUtils.get(accessTokenUrl);
        } catch (Exception e) {
            throw new YyghException(ResultCodeEnum.FETCH_ACCESSTOKEN_FAILD);
        }
        System.out.println("使用code换取的access_token结果 = " + result);
        JSONObject resultJson = JSONObject.parseObject(result);
        String accessToken = resultJson.getString("access_token");
        String openId = resultJson.getString("openid");

        //判断数据库中是否存在扫码人的微信信息
        //根据openid判断
        UserInfo userInfo =userInfoService.selectWxInfoOpenId(openId);

        if(userInfo == null){
            //第三步 使用accessToken和openId请求微信地址，最终得到扫码人信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openId);

            String resultUserInfo =null;
            try {
                resultUserInfo = HttpClientUtils.get(userInfoUrl);

            } catch (Exception e) {
                throw new YyghException(ResultCodeEnum.FETCH_USERINFO_ERROR);
            }

            System.out.println("使用access_token获取用户信息的结果 = " + resultUserInfo);

            JSONObject resultUserInfoJson = JSONObject.parseObject(resultUserInfo);

            //解析用户信息
            String nickname = resultUserInfoJson.getString("nickname");
            String headimgurl = resultUserInfoJson.getString("headimgurl");

            //获取扫码人信息 添加数据库
            userInfo = new UserInfo();
            userInfo.setOpenid(openId);
            userInfo.setNickName(nickname);
            userInfo.setStatus(1);
            userInfoService.save(userInfo);

        }



        //返回name和token字符串
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        if(StringUtils.isEmpty(userInfo.getPhone())) {
            map.put("openid", userInfo.getOpenid());
        } else {
            map.put("openid", "");
        }
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);

        //跳转前端页面
        return "redirect:" + ConstantWxPropertiesUtil.YYGH_BASE_URL
                + "/weixin/callback?token="
                +map.get("token")
                +"&openid="
                +map.get("openid")
                +"&name="+URLEncoder.encode((String) map.get("name"),"utf-8");
    }

    //1.生成微信扫描二维码
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result genQrConnect(HttpSession session){
        HashMap<String, Object> map = new HashMap<>();

        String redirectUri = null;
        try {
            //地址需要编码
            redirectUri = URLEncoder.encode(ConstantWxPropertiesUtil.WX_OPEN_REDIRECT_URL, "UTF-8");

            map.put("appid", ConstantWxPropertiesUtil.WX_OPEN_APP_ID);
            map.put("scope", "snsapi_login");
            map.put("redirectUri", redirectUri);
            map.put("state", System.currentTimeMillis()+"");
            return Result.ok(map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }


    //2.回调方法，得到扫码人的信息
}
